import SwiftUI
import PhotosUI

struct SocialMediaView: View {
    @State private var selectedPhotos: [PhotoItem] = []
    @State private var selectedPlatform: SocialPlatform = .wechat
    @State private var caption = ""
    @State private var showingPhotoPicker = false
    @State private var showingPreview = false
    
    var body: some View {
        NavigationView {
            VStack(spacing: 0) {
                // 平台选择器
                PlatformSelectorView(selectedPlatform: $selectedPlatform)
                    .padding(.horizontal)
                    .padding(.top)
                
                ScrollView {
                    VStack(spacing: 20) {
                        // 照片选择区域
                        PhotoSelectionView(
                            selectedPhotos: $selectedPhotos,
                            showingPhotoPicker: $showingPhotoPicker
                        )
                        
                        // 文案编辑区域
                        CaptionEditorView(caption: $caption, platform: selectedPlatform)
                        
                        // 分享按钮
                        ShareButtonView(
                            selectedPhotos: selectedPhotos,
                            caption: caption,
                            platform: selectedPlatform
                        ) {
                            showingPreview = true
                        }
                    }
                    .padding()
                }
            }
            .navigationTitle("社媒助手")
            .navigationBarTitleDisplayMode(.large)
            .sheet(isPresented: $showingPhotoPicker) {
                PhotoPickerView(selectedPhotos: $selectedPhotos)
            }
            .sheet(isPresented: $showingPreview) {
                SharePreviewView(
                    photos: selectedPhotos,
                    caption: caption,
                    platform: selectedPlatform
                )
            }
        }
    }
}

// 社交平台枚举
enum SocialPlatform: String, CaseIterable {
    case wechat = "微信"
    case weibo = "微博"
    case xiaohongshu = "小红书"
    case instagram = "Instagram"
    
    var icon: String {
        switch self {
        case .wechat: return "message.fill"
        case .weibo: return "globe"
        case .xiaohongshu: return "book.fill"
        case .instagram: return "camera.fill"
        }
    }
    
    var color: Color {
        switch self {
        case .wechat: return .green
        case .weibo: return .orange
        case .xiaohongshu: return .red
        case .instagram: return .purple
        }
    }
}

// 照片数据模型
struct PhotoItem: Identifiable {
    let id = UUID()
    let image: UIImage
    let originalSize: CGSize
    var editedImage: UIImage?
    
    init(image: UIImage) {
        self.image = image
        self.originalSize = image.size
        self.editedImage = image
    }
}

// 平台选择器
struct PlatformSelectorView: View {
    @Binding var selectedPlatform: SocialPlatform
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("选择平台")
                .font(.headline)
                .fontWeight(.semibold)
            
            HStack(spacing: 12) {
                ForEach(SocialPlatform.allCases, id: \.self) { platform in
                    PlatformButton(
                        platform: platform,
                        isSelected: selectedPlatform == platform
                    ) {
                        selectedPlatform = platform
                    }
                }
            }
        }
    }
}

// 平台按钮
struct PlatformButton: View {
    let platform: SocialPlatform
    let isSelected: Bool
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            VStack(spacing: 8) {
                Image(systemName: platform.icon)
                    .font(.title2)
                    .foregroundColor(isSelected ? .white : platform.color)
                
                Text(platform.rawValue)
                    .font(.caption)
                    .fontWeight(.medium)
                    .foregroundColor(isSelected ? .white : .primary)
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 12)
            .background(
                RoundedRectangle(cornerRadius: 12)
                    .fill(isSelected ? platform.color : Color(.systemGray6))
            )
        }
        .buttonStyle(PlainButtonStyle())
    }
}

// 照片选择视图
struct PhotoSelectionView: View {
    @Binding var selectedPhotos: [PhotoItem]
    @Binding var showingPhotoPicker: Bool
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Text("选择照片")
                    .font(.headline)
                    .fontWeight(.semibold)
                
                Spacer()
                
                Button("添加") {
                    showingPhotoPicker = true
                }
                .font(.subheadline)
                .foregroundColor(.accentColor)
            }
            
            if selectedPhotos.isEmpty {
                // 空状态
                Button(action: { showingPhotoPicker = true }) {
                    VStack(spacing: 12) {
                        Image(systemName: "photo.badge.plus")
                            .font(.system(size: 40))
                            .foregroundColor(.gray)
                        
                        Text("点击添加照片")
                            .font(.body)
                            .foregroundColor(.secondary)
                    }
                    .frame(maxWidth: .infinity)
                    .frame(height: 120)
                    .background(Color(.systemGray6))
                    .cornerRadius(12)
                }
                .buttonStyle(PlainButtonStyle())
            } else {
                // 照片网格
                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 3), spacing: 8) {
                    ForEach(selectedPhotos) { photo in
                        PhotoThumbnailView(photo: photo)
                    }
                }
            }
        }
    }
}

// 照片缩略图视图
struct PhotoThumbnailView: View {
    let photo: PhotoItem
    
    var body: some View {
        Image(uiImage: photo.editedImage ?? photo.image)
            .resizable()
            .aspectRatio(contentMode: .fill)
            .frame(height: 100)
            .clipped()
            .cornerRadius(8)
            .overlay(
                RoundedRectangle(cornerRadius: 8)
                    .stroke(Color.gray.opacity(0.3), lineWidth: 1)
            )
    }
}

// 文案编辑视图
struct CaptionEditorView: View {
    @Binding var caption: String
    let platform: SocialPlatform
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Text("文案编辑")
                    .font(.headline)
                    .fontWeight(.semibold)
                
                Spacer()
                
                Button("AI生成") {
                    generateAICaption()
                }
                .font(.subheadline)
                .foregroundColor(.accentColor)
            }
            
            TextField("输入文案...", text: $caption, axis: .vertical)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .lineLimit(3...6)
            
            // 平台特定提示
            Text(platformHint)
                .font(.caption)
                .foregroundColor(.secondary)
        }
    }
    
    private var platformHint: String {
        switch platform {
        case .wechat:
            return "微信朋友圈建议文案简洁，突出照片亮点"
        case .weibo:
            return "微博可以添加话题标签 #PhotoTour#"
        case .xiaohongshu:
            return "小红书文案要详细，可以分享拍摄技巧和感受"
        case .instagram:
            return "Instagram建议使用英文，添加相关hashtag"
        }
    }
    
    private func generateAICaption() {
        // 模拟AI生成文案
        let captions = [
            "今天拍到了超美的照片 📸",
            "记录生活中的美好瞬间 ✨",
            "分享一张我很喜欢的照片 💫",
            "用镜头记录世界的美好 🌍"
        ]
        caption = captions.randomElement() ?? ""
    }
}

// 分享按钮视图
struct ShareButtonView: View {
    let selectedPhotos: [PhotoItem]
    let caption: String
    let platform: SocialPlatform
    let onShare: () -> Void
    
    var body: some View {
        VStack(spacing: 12) {
            PrimaryButton(
                title: "预览分享",
                action: onShare,
                isEnabled: !selectedPhotos.isEmpty
            )
            
            if !selectedPhotos.isEmpty {
                HStack {
                    Image(systemName: "info.circle")
                        .foregroundColor(.secondary)
                    
                    Text("将分享 \(selectedPhotos.count) 张照片到 \(platform.rawValue)")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
        }
    }
}

// 照片选择器视图
struct PhotoPickerView: View {
    @Binding var selectedPhotos: [PhotoItem]
    @Environment(\.dismiss) private var dismiss
    @State private var photoSelection: PhotosPickerItem?
    @State private var photoSelections: [PhotosPickerItem] = []
    
    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                // 照片选择器
                PhotosPicker(
                    selection: $photoSelections,
                    maxSelectionCount: 9,
                    matching: .images
                ) {
                    HStack {
                        Image(systemName: "photo.badge.plus")
                            .font(.title2)
                        
                        Text("选择照片")
                            .font(.headline)
                    }
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.accentColor)
                    .cornerRadius(12)
                }
                .onChange(of: photoSelections) { _, newSelections in
                    Task {
                        await loadSelectedPhotos(from: newSelections)
                    }
                }
                
                // 已选择的照片预览
                if !selectedPhotos.isEmpty {
                    VStack(alignment: .leading, spacing: 12) {
                        Text("已选择 \(selectedPhotos.count) 张照片")
                            .font(.headline)
                            .fontWeight(.semibold)
                        
                        LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 3), spacing: 8) {
                            ForEach(selectedPhotos) { photo in
                                PhotoThumbnailView(photo: photo)
                                    .frame(height: 100)
                            }
                        }
                    }
                }
                
                Spacer()
            }
            .padding()
            .navigationTitle("选择照片")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("完成") {
                        dismiss()
                    }
                    .disabled(selectedPhotos.isEmpty)
                }
                
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        dismiss()
                    }
                }
            }
        }
    }
    
    private func loadSelectedPhotos(from selections: [PhotosPickerItem]) async {
        var newPhotos: [PhotoItem] = []
        
        for selection in selections {
            if let data = try? await selection.loadTransferable(type: Data.self),
               let image = UIImage(data: data) {
                let photoItem = PhotoItem(image: image)
                newPhotos.append(photoItem)
            }
        }
        
        await MainActor.run {
            selectedPhotos = newPhotos
        }
    }
}

// 分享预览视图
struct SharePreviewView: View {
    let photos: [PhotoItem]
    let caption: String
    let platform: SocialPlatform
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                // 平台信息
                HStack {
                    Image(systemName: platform.icon)
                        .foregroundColor(platform.color)
                        .font(.title2)
                    
                    Text("分享到 \(platform.rawValue)")
                        .font(.headline)
                        .fontWeight(.semibold)
                }
                
                // 预览内容
                ScrollView {
                    VStack(spacing: 16) {
                        // 照片预览
                        if !photos.isEmpty {
                            LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 2), spacing: 8) {
                                ForEach(photos) { photo in
                                    PhotoThumbnailView(photo: photo)
                                        .frame(height: 150)
                                }
                            }
                        }
                        
                        // 文案预览
                        if !caption.isEmpty {
                            VStack(alignment: .leading, spacing: 8) {
                                Text("文案预览")
                                    .font(.subheadline)
                                    .fontWeight(.medium)
                                
                                Text(caption)
                                    .font(.body)
                                    .padding()
                                    .background(Color(.systemGray6))
                                    .cornerRadius(8)
                            }
                        }
                    }
                    .padding()
                }
                
                // 分享按钮
                PrimaryButton(title: "确认分享", action: {
                    // 这里实现实际的分享逻辑
                    dismiss()
                })
                .padding(.horizontal)
            }
            .navigationTitle("分享预览")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("取消") {
                        dismiss()
                    }
                }
            }
        }
    }
}

#Preview {
    SocialMediaView()
} 